<?php
namespace app;
use app\util\Mysql;
use tinymeng\tools\File;

/**
 * Author: Tinymeng<666@majiameng.com>
 */
class App{

    private $model = 'index';
    private $controller = 'index';
    private $action = 'index';

    /**
     * Author: Tinymeng <666@majiameng.com>
     * @return void
     */
    public function init(){
        $this->getPath();
        $this->loadFile();
        $this->loadConfig();
        $this->loadUtil();
        $this->analyzeUrl();
        if((!defined("MODEL") || MODEL!='install') && !file_exists(INSTALL_PATH.DIRECTORY_SEPARATOR.'install.lock')){
            header("Location: ".getUrl('install'));exit();
        }elseif((!defined("MODEL") || MODEL!='install')){
            if(!defined("RESTRICT_ACCESS") || RESTRICT_ACCESS!=false){
                $this->restrictAccess();
            }
        }
        return $this;
    }

    /**
     * Author: Tinymeng <666@majiameng.com>
     * @return void
     */
    public function getPath(){
        define('NOW_TIME',time());
        define('APP_PATH',dirname(__DIR__));
        define('CONFIG_PATH',APP_PATH.DIRECTORY_SEPARATOR.'config');
        define('PUBLIC_PATH',APP_PATH.DIRECTORY_SEPARATOR.'public');
        define('INSTALL_PATH',APP_PATH.DIRECTORY_SEPARATOR.'app/install');
    }

    /**
     * Author: Tinymeng <666@majiameng.com>
     * @return void
     */
    public function loadFile(){
        require APP_PATH . '/vendor/autoload.php';
        require APP_PATH . '/app/controller.php';
    }
    /**
     * Author: Tinymeng <666@majiameng.com>
     * @return void
     */
    public function loadConfig(){
        define('DATABASE_CONFIG',require CONFIG_PATH .DIRECTORY_SEPARATOR. 'database.php');
        define('APP_CONFIG',require CONFIG_PATH .DIRECTORY_SEPARATOR. 'app.php');
        // 开启session
        if(APP_CONFIG['session']){
            session_start();
        }
        // 设置时区
        if(APP_CONFIG['time_zone']){
            date_default_timezone_set(APP_CONFIG['time_zone']);
        }
    }

    /**
     * Author: Tinymeng <666@majiameng.com>
     * @return void
     */
    public function loadUtil(){
        $path = APP_PATH.DIRECTORY_SEPARATOR.'app'.DIRECTORY_SEPARATOR.'util';
        $this->requirePath($path);
    }

    /**
     * Author: Tinymeng <666@majiameng.com>
     * @param $path
     * @return void
     */
    public function requirePath($path){
        foreach (File::scanDir($path) as $filename){
            $file = $path.DIRECTORY_SEPARATOR.$filename;
            if(is_file($file) && $this->isPhpFile($file)){
                require $file;
            }
        }
    }

    public function isPhpFile($filePath) {
        $extension = pathinfo($filePath, PATHINFO_EXTENSION);
        return strtolower($extension) === 'php';
    }

    /**
     * Author: Tinymeng <666@majiameng.com>
     * @return void
     */
    public function start(){
        $this->requirePath(APP_PATH.DIRECTORY_SEPARATOR.'app'.DIRECTORY_SEPARATOR.$this->model);
        $class = '\app\\'.$this->model.'\\'.ucfirst($this->controller);
        if(class_exists($class) && @method_exists($class,$this->action)){
            $action = $this->action;
            (new $class)->$action();
        }else{
            error('404');
        }
    }

    /**
     * @return void
     */
    public function analyzeUrl(){
        $mca = getMca($this->model,$this->controller,$this->action);
        $this->model = $mca['model'];
        $this->controller = $mca['controller'];
        $this->action = $mca['action'];
        define('MODEL',$this->model);//模块
    }



    /**
     * 限制访问（检测ip白名单）
     * define('RESTRICT_ACCESS',false);//关闭检测访问
     * @return void
     */
    public function restrictAccess(){
        $database = Mysql::init();
        $safe = $database->select("sys_config", ["name", "value"]); //请求数据库数据

        $output_array = array_column($safe, "value", "name");

        if (isset($output_array['safe_mode'])) {
            $client_ip = getClientIP();

            if ($client_ip != "127.0.0.1") {

                if ($output_array['safe_mode'] == 1) { //黑名单模式

                    if ($output_array['black_ips']) {
                        // 获取黑名单 IP 列表
                        $blacklist_ips = str_replace(',', '|', $output_array['black_ips']);
                        $ip_pattern = str_replace('.', '\.', $blacklist_ips); // 转义点号
                        $ip_pattern = str_replace('*', '.*', $ip_pattern);

                        if (preg_match('/' . $ip_pattern . '/', $client_ip)) {
                            // 如果客户端 IP 匹配了黑名单 IP 段，则进行屏蔽操作
                            echo "Not found";
                            exit;
                        }
                    }
                } else { //白名单模式
                    if (!$output_array['white_ips']) {
                        echo "Not found";
                        exit;
                    }
                    $whitelist_ips = str_replace(',', '|', $output_array['white_ips']);
                    $ip_pattern = str_replace('.', '\.', $whitelist_ips);
                    $ip_pattern = str_replace('*', '.*', $ip_pattern);
                    if (!preg_match('/' . $ip_pattern . '/', $client_ip)) {
                        // 如果客户端 IP 未匹配了白名单 IP 段，则进行屏蔽操作
                        echo "Not found";
                        exit;
                    }
                }
            }
        }
    }


}
return (new App())->init();
